package com.paradogs.generator.idl;


import com.baidu.bjf.remoting.protobuf.ProtobufIDLGenerator;
import com.paradogs.framework.core.annoations.base.BaseScanner;
import com.paradogs.framework.core.annoations.base.BaseSelector;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: yumi
 * @date: 2023/11/18  10:55
 * @Description: TODO
 */
@Slf4j
@Component
public class ProtoEntitySelector extends BaseSelector {

    @Setter
    private String generatorDir;

    @Setter
    private String[] scanPackages;

    private Set<Class<?>> cachedTypes = new HashSet<>();

    private Set<Class<?>> cachedEnumTypes = new HashSet<>();

    @Override
    public String[] getScanPackages() {
        return scanPackages;
    }

    @Override
    public BaseScanner getScanner(BeanFactory beanFactory) {
        return new ProtoEntityScanner((DefaultListableBeanFactory) beanFactory);
    }

    /**
     * 生成 .proto 文件
     * @param beanDefinition
     */
    @Override
    public void handle(BeanDefinition beanDefinition) {
        try {
            Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
            String filename = beanClass.getSimpleName() + ".proto"; // 文件名
//            String code = ProtobufIDLGenerator.getIDL(beanClass, cachedTypes, cachedEnumTypes); // 文件内容
            String code = ProtobufIDLGenerator.getIDL(beanClass);
            Path targetDirectory = Paths.get(this.generatorDir);
            Path filePath = targetDirectory.resolve(filename);

            // 确保目录存在
            Files.createDirectories(targetDirectory);

            // 写入内容到文件
            Files.write(filePath, code.getBytes());
            log.info("生成文件: {}/{}", generatorDir, filename);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
